<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>信息流管理</el-breadcrumb-item>
      <el-breadcrumb-item>
        <span
          class="u-cursor"
          @click="$router.back()"
        >客户资质管理</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{pageTitle}}客户资质</el-breadcrumb-item>
    </el-breadcrumb>
    <Container class="u-pb60">
      <el-form
        class="m-form--detail"
        label-width="160px"
        :model="pageData"
        :rules="pageRules"
        ref="pageForm"
      >
        <ContainerTitle>营业执照</ContainerTitle>
        <el-form-item label-width="43px">
          <el-alert
            class="u-w500"
            type="warning"
            :closable="false"
          >
            1、注意：修改客户资质后，其他模块涉及的客户资质内容会同步更改！
          </el-alert>
        </el-form-item>
        <el-form-item
          required
          prop="customerFullName"
          size="small"
          label="客户全称："
        >
          <el-autocomplete
            class="u-w350"
            clearable
            v-model.trim="pageData.customerFullName"
            :disabled="pageAction === 'detail'"
            :fetch-suggestions="customerQuerySearch"
            placeholder="请输入客户名称"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item
          size="small"
          label="营业执照号："
        >
          <el-input
            class="u-w350"
            placeholder="请输入营业执照号"
            :disabled="pageAction === 'detail'"
            v-model.trim="pageData.businessLicenseNo"
          ></el-input>
        </el-form-item>
        <el-form-item
          size="small"
          label="营业执照期限："
        >
          <el-date-picker
            class="u-w170"
            type="date"
            placeholder="开始日期"
            value-format="yyyy-MM-dd"
            :disabled="pageAction === 'detail'"
            v-model="pageData.startDate"
          >
          </el-date-picker>
          <el-date-picker
            class="u-w170 u-ml10"
            type="date"
            placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :disabled="pageAction === 'detail' || pageData.permanent === 1"
            v-model="pageData.endDate"
          >
          </el-date-picker>
          <el-checkbox
            label="长期"
            class="u-ml10"
            :disabled="pageAction === 'detail'"
            :true-label="1"
            :false-label="0"
            v-model="pageData.permanent"
            @change="pageData.endDate = ''"
          ></el-checkbox>
        </el-form-item>
        <el-form-item
          size="small"
          label="营业执照地址："
        >
          <el-input
            class="u-w350"
            type="textarea"
            placeholder="请输入营业执照地址"
            :disabled="pageAction === 'detail'"
            v-model.trim="pageData.businessLicenseAddress"
          ></el-input>
        </el-form-item>

        <ContainerTitle>财务信息</ContainerTitle>
        <el-form-item
          size="small"
          label="纳税人登记号："
        >
          <el-input
            class="u-w350"
            placeholder="请输入纳税人登记号"
            :disabled="pageAction === 'detail'"
            v-model.trim="pageData.taxpayerRegistr"
          ></el-input>
        </el-form-item>
        <el-form-item
          size="small"
          label="开户行："
        >
          <el-input
            class="u-w350"
            placeholder="请输入开户行"
            :disabled="pageAction === 'detail'"
            v-model.trim="pageData.depositBank"
          ></el-input>
        </el-form-item>
        <el-form-item
          size="small"
          label="银行账号："
        >
          <el-input
            class="u-w350"
            placeholder="请输入银行账号"
            :disabled="pageAction === 'detail'"
            v-model.trim="pageData.bankAccount"
            @input.native="handleBankAccount"
          ></el-input>
        </el-form-item>
        <el-form-item
          size="small"
          label="开户地址："
        >
          <el-input
            type="textarea"
            class="u-w350"
            placeholder="请输入开户地址"
            :disabled="pageAction === 'detail'"
            v-model.trim="pageData.depositAddress"
          ></el-input>
        </el-form-item>
        <el-form-item
          size="small"
          label="开票电话号码："
        >
          <el-input
            class="u-w350"
            placeholder="请输入开票电话号码"
            :disabled="pageAction === 'detail'"
            v-model.trim="pageData.invoicePhone"
          ></el-input>
        </el-form-item>

        <ContainerTitle>关联客户</ContainerTitle>
        <el-form-item label="关联客户：">
          <el-select
            size="small"
            class="u-w350"
            filterable
            :disabled="pageAction === 'detail'"
            v-model="pageData.customerId"
          >
            <el-option
              v-for="item in customerOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <template v-if="pageAction === 'detail'">
          <el-form-item label="客户状态：">{{pageData.status}}</el-form-item>
          <el-form-item label="最后操作人：">{{pageData.updateBy}}</el-form-item>
          <el-form-item label="最后操作时间：">{{pageData.updateTime}}</el-form-item>
        </template>
      </el-form>
    </Container>
    <Affix :offset-bottom="0">
      <ButtonGroup
        isFixed
        align="right"
      >
        <el-button
          size="small"
          @click="$router.back()"
        >返回</el-button>
        <el-button
          size="small"
          type="primary"
          v-if="['create', 'edit'].includes(pageAction)"
          @click="handleEnsure"
        >确定</el-button>
      </ButtonGroup>
    </Affix>
  </div>
</template>

<script>
import ContainerTitle from "@/components/container-title";
import Container from "@/components/container";
import Affix from "@/components/affix";
import ButtonGroup from "@/components/button-group";

import { getStrLen } from "@/util";

export default {
  components: {
    ContainerTitle,
    Container,
    Affix,
    ButtonGroup
  },
  data() {
    return {
      pageAction: this.$route.query.action,

      // 客户名称
      customerOptions: [],

      pageData: {
        customerFullName: "",
        businessLicenseNo: "",
        startDate: "",
        endDate: "",
        permanent: 0,
        businessLicenseAddress: "",
        taxpayerRegistr: "",
        depositBank: "",
        bankAccount: "",
        depositAddress: "",
        invoicePhone: "",
        customerId: ""
      },
      pageRules: {
        customerFullName: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value || value.trim() === "") {
              callback(new Error("请输入客户名称"));
            } else if (getStrLen(value) > 50) {
              callback(new Error("客户名称最多50个字符"));
            } else {
              callback();
            }
          },
          trigger: ["change", "blur"]
        }
      }
    };
  },
  computed: {
    pageTitle() {
      return {
        create: "新增",
        edit: "编辑",
        detail: "查看"
      }[this.pageAction];
    }
  },
  methods: {
    // 银行账号间隔
    handleBankAccount(e) {
      this.pageData.bankAccount = this.formatBankAccount(e.target.value);
    },
    // 格式化银行账号
    formatBankAccount(value) {
      return this.unFormatBankAccount(value).replace(/(\d{4})(?=\d)/g, "$1 ");
    },
    // 格式化银行账号
    unFormatBankAccount(value) {
      return value.replace(/\s/g, "");
    },
    // 客户名称搜索
    customerQuerySearch(queryString, cb) {
      let results = queryString
        ? this.customerOptions.filter(this.customerQueryFilter(queryString))
        : this.customerOptions;
      cb(results);
    },
    customerQueryFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    fetchCustomerOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/customer/get_customer_name",
        params: {
          status: ["edit", "detail"].includes(this.pageAction)? 0 : 2
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.customerOptions = res.data.data.map(item => {
            return {
              ...item,
              value: item.name
            };
          });
        }
      });
    },
    // 确定
    handleEnsure() {
      if (this.pageAction === "edit") {
        this.updateDetail();
      } else {
        this.createDetail();
      }
    },
    // 新建
    createDetail() {
      this.$refs.pageForm.validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/manage/api/bus/customer_aptitude/add",
            data: {
              ...this.pageData,
              bankAccount: this.unFormatBankAccount(this.pageData.bankAccount)
            }
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("新建成功！");
              this.$router.back();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        }
      });
    },
    // 编辑
    updateDetail() {
      this.$refs.pageForm.validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/manage/api/bus/customer_aptitude/update",
            data: {
              ...this.pageData,
              bankAccount: this.unFormatBankAccount(this.pageData.bankAccount)
            }
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("修改成功！");
              this.$router.back();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        }
      });
    },
    // 详情
    getDetail() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/customer_aptitude/get_by_id",
        params: {
          customerAptitudeId: this.$route.query.id
        }
      }).then(res => {
        if (res.data.code === 0) {
          if (this.pageAction === "edit") {
            let {
              id,
              customerFullName,
              businessLicenseNo,
              startDate,
              endDate,
              permanent,
              businessLicenseAddress,
              taxpayerRegistr,
              depositBank,
              bankAccount,
              depositAddress,
              invoicePhone,
              customerId
            } = res.data.data;
            this.pageData = {
              id,
              customerFullName,
              businessLicenseNo,
              startDate,
              endDate,
              permanent,
              businessLicenseAddress,
              taxpayerRegistr,
              depositBank,
              bankAccount: this.formatBankAccount(bankAccount),
              depositAddress,
              invoicePhone,
              customerId
            };
          } else {
            this.pageData = res.data.data;
          }
        }
      });
    }
  },
  created() {
    this.fetchCustomerOptions();
    if (["edit", "detail"].includes(this.pageAction)) {
      this.getDetail();
    }
  }
};
</script>